--local dlog = require 'dlog'
--local utils = require 'utils'

local function requestAd()
    local nut_module = require 'nut_module'
    local router = require 'router'


    ngx.req.read_body()
    local nut = nut_module.Nut:new(nil)

    local status, err = pcall(
        function()
            -- router process
            router.doRouter(nut)
        end
    )


    -- server error occurred, return 404
    if not status then
        nut.http_rsp.body = '500 INTERNAL_SERVER_ERROR'
        nut.http_rsp.code = ngx.HTTP_INTERNAL_SERVER_ERROR
        ngx.log(ngx.ERR, err)
    end

    return nut.http_rsp.body, nut.http_rsp.code
end

local function httpd()
    local status, result, code = pcall(
        function()
            return requestAd()
        end
    )

    if status then
        -- js script cross-domain
        ngx.header['Content-Type'] = 'application/json'
        ngx.header['Access-Control-Allow-Origin'] = '*'
        ngx.header['Access-Control-Allow-Headers'] = 'Content-Type, x-bridge-version, x-vendor-id, x-is-test'
        ngx.status = code
        ngx.say(result)
        ngx.exit(code)
    else
        ngx.log(ngx.ERR, result)
        ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
        ngx.say('500 INTERNAL_SERVER_ERROR')
        ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    end
end

httpd()
